package com.example.tuter.util.httpUtil;

import static com.example.tuter.util.httpUtil.HttpCodeConstant.UNAUTHORIZED;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.tuter.MyApplication;
import com.example.tuter.activity.WebViewActivity;
import com.example.tuter.entity.Message;
import com.example.tuter.util.Constant;
import com.example.tuter.util.CookieUtil;
import com.example.tuter.util.SPUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitFactory {
    private static Retrofit ssfwRetrofit = null;
    private static Retrofit baseRetrofit = null;
    //测试环境下需要将这个
    private static final String LocalAddress = "http://192.168.1.114:8084";


    private RetrofitFactory() {
    }

    //获取学校信息门户的工厂
    public static Retrofit getSchoolInstance() {



        if (ssfwRetrofit == null) {
            OkHttpClient.Builder client = new OkHttpClient.Builder();
            client.addInterceptor(new Interceptor() {
                @NonNull
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    final Request.Builder builder = chain.request().newBuilder();
                    //添加Cookie
                    if (Constant.schoolCookie != null) {
                        builder.addHeader("Cookie", CookieUtil.getCookieFromCookieClass(Constant.schoolCookie));
                    }
                    return chain.proceed(builder.build());
                    //这里应该添加一个回来得拦截器，如果cookie已经过期了，提示用户可能需要重新登录
                }
            });
            ssfwRetrofit = new Retrofit.Builder()
                    //设置数据解析器
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl("http://none.com")
                    .build();
        }

        return ssfwRetrofit;
    }

    public static Retrofit getBaseInstance() {


        if (baseRetrofit == null) {
            OkHttpClient.Builder client = new OkHttpClient.Builder();

            client.addInterceptor(chain -> {

                //添加前拦截器，自动添加token
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("token", SPUtils.getToken(MyApplication.getContext()))
                        .method(original.method(), original.body())
                        .build();
                //response为返回
                Response response = chain.proceed(request);
                //检查返回值，在这里做一些公共的操作
                checkReturn(response);


                return response;
            });
            OkHttpClient httpClient = client.build();
            baseRetrofit = new Retrofit.Builder()
                    //设置数据解析器
                    .addConverterFactory(GsonConverterFactory.create())
                    //设置网络请求BaseUrl地址
//                    .baseUrl(String.valueOf(R.string.server_address))
                    .baseUrl(LocalAddress)
                    .client(httpClient)
                    .build();

        }
        return baseRetrofit;
    }

    private static void checkReturn(Response response) throws IOException {
        ResponseBody responseBody = response.body();
        assert responseBody != null;
        //解决response.body().string();只能打印一次
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.getBuffer();
        Charset UTF8 = StandardCharsets.UTF_8;
        String string = buffer.clone().readString(UTF8);

        Message<Object> message = JSONObject.parseObject(string, new TypeReference<Message<Object>>() {
        });
        Context context = MyApplication.getContext();
        int code = message.getCode();
        //自动更新token
        String token = response.header("token");
        if (token != null) {
            reset();
            SPUtils.putToken(context, token);
        } else if (code == UNAUTHORIZED.getValue()) {
            //跳转登录
            Intent intent = new Intent(context, WebViewActivity.class);
            context.startActivity(intent);

        }
    }


    //一般在登录以后，或者重新登录的时候，需要重新加载token
    public static void reset() {
        ssfwRetrofit = null;
        baseRetrofit = null;
    }
}
